package com.five.controller;


import com.alibaba.fastjson.JSON;
import com.five.entity.User;
import com.five.entity.UserParticipant;
import com.five.service.UserParticipantService;
import com.five.service.UserService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by Administrator on 2018/1/12.
 */

@RestController
@RequestMapping("/youxue")
public class UserController {

    private static final Logger looger = Logger.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private UserParticipantService userParticipantService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpSession session;

    @RequestMapping(value = "/users",method = RequestMethod.GET)
    public String registerUser(@RequestParam("username") String username,
                               @RequestParam("password") String password,
                               @RequestParam("type") String type,
                               @RequestParam("idnumber") String idnumber){

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setType(type);
        user.setIdnumber(idnumber);
        userService.addUser(user);

        return JSON.toJSONString("register success");
    }

    @RequestMapping(value = "/users/login",method = RequestMethod.GET,produces ="text/plain;charset=UTF-8" )
    public String login(@RequestParam("idnumber") String idnumber,
                        @RequestParam("password") String password){

        User current = userService.getUserByIdnumber(idnumber);
        try {
            session = request.getSession();
            session.setMaxInactiveInterval(180000);
            session.setAttribute("userLogin",current);
            return session.getId()+","+current.getUserId();
        }catch (Exception e){}

        return "";
    }

    @RequestMapping(value = "/users/changePassword",method = RequestMethod.GET)
    public String changePassword(@RequestParam("idnumber") String idnumber,
                                 @RequestParam("password") String password){

        User currentUser = userService.getUserByIdnumber(idnumber);
        try {
            looger.info(currentUser.toString());
            currentUser.setPassword(password);
            currentUser.setUserId(currentUser.getUserId());
            userService.changePassword(currentUser);
            return "modification success";
        }catch (NullPointerException e){
            return "modification failure";
        }

    }

    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public void logout(){

        session.invalidate();

    }


    /**
     * 我的钱包-》账号余额
     * @return
     */
    @RequestMapping(value = "/accountBalance",method = RequestMethod.GET)
    public int accountBalance(){
        User currentUser =
                (User) session.getAttribute("userLogin");
        try {
            return currentUser.getAccountBalance();
        }catch (NullPointerException e){
            return 0;
        }
    }

    /**
     * 我的钱包-》充值
     */
    @RequestMapping(value = "/recharge",method = RequestMethod.GET)
    public void recharge(@RequestParam("accountBalance") Integer account){

        User currentUser =
                (User) session.getAttribute("userLogin");
        try {
            looger.info(currentUser.getUserId());
            if (currentUser.getAccountBalance()==null){
                currentUser.setAccountBalance(account);
            }else {
                currentUser.setAccountBalance(currentUser.getAccountBalance()+account);
            }
            currentUser.setUserId(currentUser.getUserId());
            userService.changeMoney(currentUser);
        }catch (NullPointerException e){
        }
    }

    /**
     * 我的钱包-》设置支付密码-》修改支付密码
     * @param payPassword
     * @return
     */
    @RequestMapping(value = "/payPassword",method = RequestMethod.GET)
    public String setPayPassword(@RequestParam("payPassword") Integer payPassword){

        User currentUser =
                (User) session.getAttribute("userLogin");
        try {
            currentUser.setPayPassword(payPassword);
            currentUser.setUserId(currentUser.getUserId());
            userService.changePayPassword(currentUser);
            return "modification success";
        }catch (NullPointerException e){
            return "modification failure";
        }
    }


    /**
     * 用户头像上传或者更新->待测试
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadUserAvatar",method = RequestMethod.POST)
    public String uploadUserAvatar(@RequestParam("file")MultipartFile file){

        String savePath = "F:\\AllJavaWeb\\YouXue\\src\\main\\webapp\\upload";

        String newFileName = null;
        String filePath = null;
        String suffixName = null;

        if(file!=null && !file.isEmpty()){
            //获取文件名称
            String fileName=file.getOriginalFilename();
            //获取后缀名
            suffixName=fileName.substring(fileName.indexOf(".") + 1);
            //新文件名称
            newFileName=System.currentTimeMillis()+"."+suffixName;
            //新文件路劲
            filePath=savePath+"\\"+newFileName;
            //获取存储文件路径
            File fileDir=new File(savePath);
            if(!fileDir.exists()){
                //如果文件夹没有：新建
                fileDir.mkdirs();
            }
            FileOutputStream fos=null;
            try {
                fos=new FileOutputStream(filePath);
                fos.write(file.getBytes());
                fos.flush();
            } catch (Exception e){
                e.printStackTrace();

            } finally{
                try {
                    if(fos!=null){
                        fos.close();
                    }
                } catch (IOException e){
                    e.printStackTrace();

                }
            }
        }
        User currentUser =
                (User) session.getAttribute("userLogin");
        try {
            currentUser.setUserAvatar("upload" + "/" + newFileName);
            currentUser.setUserId(currentUser.getUserId());
            userService.uploadAvatar(currentUser);
            return "{\"result\":\"true\",\"msg\":\"success\"}";
        }catch (Exception e){
            return "{\"result\":\"false\",\"msg\":"+e.getMessage()+"}";
        }

    }

    @RequestMapping(value = "/editMyInfoNickname",method = RequestMethod.GET)
    public void editMyInfo1(@RequestParam("nickname") String nickname){
        User currentUser =
                (User) session.getAttribute("userLogin");
        currentUser.setNickname(nickname);
        currentUser.setUserId(currentUser.getUserId());
        userService.updateMyInfo(currentUser);

    }

    @RequestMapping(value = "/editMyInfoUsername",method = RequestMethod.GET)
    public void editMyInfo2(@RequestParam("username") String username){
        User currentUser =
                (User) session.getAttribute("userLogin");
        currentUser.setUsername(username);
        currentUser.setUserId(currentUser.getUserId());
        userService.updateMyInfo(currentUser);

    }

    @RequestMapping(value = "/editMyInfosex",method = RequestMethod.GET)
    public void editMyInfo3(@RequestParam("sex") String sex){
        User currentUser =
                (User) session.getAttribute("userLogin");
        currentUser.setSex(sex);
        currentUser.setUserId(currentUser.getUserId());
        userService.updateMyInfo(currentUser);

    }

    @RequestMapping(value = "/editMyInfoBirth",method = RequestMethod.GET)
    public void editMyInfo4(@RequestParam("birthday")String birthday){
        User currentUser =
                (User) session.getAttribute("userLogin");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            currentUser.setBirthday(sdf.parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        currentUser.setUserId(currentUser.getUserId());
        userService.updateMyInfo(currentUser);

    }

    @RequestMapping(value = "/editMyInfoPro",method = RequestMethod.GET)
    public void editMyInfo5(@RequestParam("professional") String professional){
        User currentUser =
                (User) session.getAttribute("userLogin");
        currentUser.setProfessional(professional);
        currentUser.setUserId(currentUser.getUserId());
        userService.updateMyInfo(currentUser);

    }

    @RequestMapping(value = "/editMyInfoArea",method = RequestMethod.GET)
    public void editMyInfo6(@RequestParam("area") String area){
        User currentUser =
                (User) session.getAttribute("userLogin");
        currentUser.setArea(area);
        currentUser.setUserId(currentUser.getUserId());
        userService.updateMyInfo(currentUser);

    }

    @RequestMapping(value = "/editMyInfoEmail",method = RequestMethod.GET)
    public void editMyInfo7(@RequestParam("email") String email){
        User currentUser =
                (User) session.getAttribute("userLogin");
        currentUser.setEmail(email);
        currentUser.setUserId(currentUser.getUserId());
        userService.updateMyInfo(currentUser);

    }

    /**
     * 用户->我的信息->展示  账号用身份证表示
     * @return
     */
    @RequestMapping(value = "/showMyInfo",method = RequestMethod.GET,produces ="text/plain;charset=UTF-8")
    public String showMyInfo(){
        User currentUser =
                (User) session.getAttribute("userLogin");
        User user = userService.getUserById(currentUser.getUserId());
        return JSON.toJSON(user).toString();
    }




    /**
     * 用户的参加人信息
     * @return
     */
    @RequestMapping(value = "/showUserParticipant",method = RequestMethod.GET,produces ="text/plain;charset=UTF-8")
    public String showUserParticipant(){
        User currentUser =
                (User) session.getAttribute("userLogin");
        List<UserParticipant> list;
        try {
            list = userParticipantService.selectByUserId(currentUser.getUserId());
            return JSON.toJSON(list).toString();
        }catch (Exception e){
            looger.info(e.getMessage());
            return "";
        }
    }

    /**
     * 用户增加参加人信息
     * @param username
     * @param idnumber
     * @return
     */
    @RequestMapping(value = "/addUserParticipant",method = RequestMethod.GET)
    public void addUserParticipant(@RequestParam("username") String username,
                                     @RequestParam("idnumber") String idnumber){

        User currentUser =
                (User) session.getAttribute("userLogin");
        UserParticipant userParticipant = new UserParticipant();
        userParticipant.setUsername(username);
        userParticipant.setIdnumber(idnumber);
        userParticipant.setUserid(currentUser.getUserId());
        userParticipantService.addUserParticipant(userParticipant);
    }


    /**
     * 用户删除参加人信息
     * @param id
     */
    @RequestMapping(value = "/deleteUserParticipant",method = RequestMethod.GET)
    public void deleteUserParticipant(@RequestParam("userParticipantId") Integer id){

        userParticipantService.deleteUserParticipant(id);
    }



}
